<template>
  <div style="margin-top: 20px;">
    <h3>折线图</h3>
    <BasicForm @register="register" @submit="handleSubmit" />
    <div ref="chartRef" :style="{ height, width }"></div>
  </div>
</template>

<script lang="ts" setup>
  import { PropType, ref, Ref } from 'vue';
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { useECharts } from '@/hooks/web/useECharts';

  const props = defineProps({
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: 'calc(100vh - 78px)',
    },
    queryResult: [],
    keyOptions: [],
  });

  const formSchema: FormSchema[] = [
    {
      field: 'x',
      label: 'X轴',
      component: 'Select',
      required: true,
      componentProps: {
        options: props.keyOptions,
      },
    },
    {
      field: 'y',
      label: 'Y轴',
      component: 'Select',
      required: true,
      componentProps: {
        options: props.keyOptions,
      },
    },
    {
      field: 'categoryKey',
      label: '分类字段',
      component: 'Select',
      componentProps: {
        options: props.keyOptions,
      },
    },
  ];

  const [register] = useForm({
    baseColProps: { span: 10 },
    labelWidth: 80,
    showActionButtonGroup: true,
    schemas: formSchema,
  });

  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
  
  function handleSubmit(values) {
    let xData = [];
    let legends = [];
    let legendDataMap = new Map();
    for (const item of props.queryResult) {
      const legend = String(values.categoryKey ? item[values.categoryKey] : '');
      const x = item[values.x];
      const y = item[values.y];
      if (!legends.includes(legend)) {
        legends.push(legend);
      }
      if (!xData.includes(x)) {
        xData.push(x);
      }
      if (!legendDataMap.has(legend)) {
        legendDataMap.set(legend, new Map());
      }
      if (!legendDataMap.get(legend).has(x)) {
        legendDataMap.get(legend).set(x, 0);
      }
      legendDataMap.get(legend).set(x, legendDataMap.get(legend).get(x) + y);
    }
    
    let series = [];
    for (const legend of legends) {
      let yData = [];
      for (const x of xData) {
        const y = legendDataMap.get(legend).get(x);
        yData.push(y);
      }
      series.push({
        name: legend,
        type: 'line',
        data: yData
      });
    }

    setOptions({
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: legends
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xData,
      },
      yAxis: {
        type: 'value'
      },
      series: series,
    });
  };

</script>